package model

import (
    adapter "git.inspur.com/x/iam-adapter-go"
    "git.inspur.com/x/iam-adapter-go/resource"
    "git.inspur.com/x/models"
)

type GroupPage struct {
    TotalCount int64    `json:"totalCount" valid:"-"`
    PageNo     int      `json:"pageNo" valid:"-"`
    PageSize   int      `json:"pageSize" valid:"-"`
    Data       []*Group `json:"data" valid:"-"`
}

type Group struct {
    Id          string      `xorm:"pk" json:"id" valid:"-" `
    Name        string      `json:"name" valid:"-"`
    DisplayName string      `json:"displayName" valid:"-"`
    Creator     string      `json:"creator" valid:"-"`
    A5tId       string      `xorm:"account_id" json:"accountId" valid:"-"`
    CreatorName string      `json:"creatorName" valid:"-"`
    A5tName     string      `xorm:"account_name" json:"accountName" valid:"-"`
    RegionCode  string      `json:"regionCode" valid:"-" `
    RegionName  string      `json:"regionName" valid:"-" `
    Description string      `json:"description" valid:"-"`
    CreateTime  models.Time `xorm:"created" json:"createTime" valid:"-" `
    UpdateTime  models.Time `xorm:"updated" json:"updateTime" valid:"-" `
    DeleteTime  models.Time `xorm:"deleted" json:"deleteTime" valid:"-" `
}

func CreateGroup(group *Group) (*Group, error) {
    _, err := models.Engine.Table("fcs_group").InsertOne(group)
    if err != nil {
        _ = logger.Error("Insert group err : ", err)
        return nil, err
    }
    return group, nil
}

func DeleteGroup(id string) error {
    if _, err := models.Engine.Table("fcs_group").ID(id).Delete(new(Trigger)); err != nil {
        _ = logger.Error("Delete group err : ", err)
        return err
    }
    return nil
}

func UpdateGroup(group *Group) (*Group, error) {
    if _, err := models.Engine.Table("fcs_group").ID(group.Id).Cols("display_name").Cols("description").Update(group); err != nil {
        _ = logger.Error("Update group err : ", err)
        return nil, err
    }
    return group, nil
}

func GetGroupList(user *resource.User, pageNo, pageSize int, name string) (*GroupPage, error) {
    var gs []*Group
    session := models.Engine.Table("fcs_group").OrderBy("update_time desc")
    if name != "" {
        session = session.Where("INSTR(fcs_group.display_name,?)", name)
    }
    if err := session.Find(&gs, &Group{A5tId: user.AccountId}); err != nil {
        _ = logger.Error("Get groupList err : ", err)
        return nil, err
    }

    filteredList := adapter.FilterListData(gs).([]interface{})
    resultList := make([]*Group, 0)
    for _, g := range filteredList {
        g, ok := g.(*Group)
        if ok {
            resultList = append(resultList, g)
        }
    }

    count := len(resultList)
    pageStart := (pageNo - 1) * pageSize
    pageEnd := pageNo * pageSize
    if pageStart > count-1 {
        pageStart = 0
        pageEnd = 0
    } else if pageEnd > count {
        pageEnd = count
    }

    gp := &GroupPage{
        TotalCount: int64(count),
        PageNo:     pageNo,
        PageSize:   pageSize,
        Data:       resultList[pageStart:pageEnd],
    }

    return gp, nil
}

func GetGroupById(id string) (*Group, error) {
    g := &Group{}
    if _, err := models.Engine.Table("fcs_group").ID(id).Get(g); err != nil {
        _ = logger.Error("Get Group By Id err : ", err)
        return nil, err
    }
    return g, nil
}

func CheckGroupExist(uid, displayName string) (bool, error) {
    g := &Group{}
    return models.Engine.Table("fcs_group").Where("account_id=?", uid).And("display_name=?", displayName).Exist(g)
}

func GetGroupByUserAndId(user *resource.User, id string) (*Group, error) {
    g := &Group{}
    has, err := models.Engine.Table("fcs_group").Where("account_id=?", user.AccountId).And("id=?", id).Get(g)
    if err != nil {
        _ = logger.Error("GetGroupByUserAndId err : ", err)
        return nil, InternalServerError(GroupGetError, err.Error())
    }
    if !has {
        _ = logger.Warn("GetGroupByUserAndId: did not find func_info, groupId=%v, userId=%v", id, user.Id)
        return nil, InternalServerError(GroupGetError, "没有找到函数数据")
    }
    return g, nil
}
